<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2019/3/21
 * Time: 9:18
 */

namespace app\api\controller;


use think\Db;

class Login extends Base
{
    /**
     * 发送验证码
     * @return \think\response\Json|void
     * phone：填写的手机号
     * type：   1 注册   2 短信快捷登录||忘记密码  3 第三方登录时绑定手机号    其他传空
     * types:  当type为3时，传此值  1 微信  2 qq  3 微博
     * return:  0 请输入手机号   1 手机号格式不正确  2 该手机号已注册  3 没有此手机号的用户
     *          4 此号码已被绑定  5 短信验证码今日已发送5次，请明天再来  6 云之讯返回错误  7 操作数据库失败
     *          200  返回验证码
     */
    public function getPhoneCode()
    {
        $params = input('param.');
        if(trim($params['phone'], ' ') == '') {
            return json(['status' => 0, 'msg' => '请输入手机号']);
        }
        if(!preg_match("/^1[3456789]\d{9}$/", $params['phone'])) {
            return json(['status' => 0, 'msg' => '手机号格式不正确']);
        }
//        $time = $_SERVER['HTTP_REQDATE'];
//        $reqKey = $_SERVER['HTTP_REQKEY'];
//        $appId = "A6070308312682";
//        $appkey = "9AF807B0-BE12-F521-6998-6D57B0CCE8BB";
//        $myreqKey = md5($appId . 'XW' . $appkey . 'XW' . $time);
//        if($myreqKey != $reqKey){
//            return json(['status'=>1,'msg'=>'非法来源']);
//        }
        $userInfo = Db::table('up_u_user')->where('user_phone', $params['phone'])->find();
        if(!empty($userInfo) && $params['type'] == 1) {//注册
            return json(['status' => 0, 'msg' => '该手机号已注册']);
        }
        if(empty($userInfo) && $params['type'] == 2) {//短信快捷登录||忘记密码
            return json(['status' => 0, 'msg' => '该账号不存在']);
        }
        if(!empty($userInfo) && $params['type'] == 3) {//第三方登录时绑定手机号
            if($params['types'] == 1) {
                $field = '_wx_';
            } elseif($params['types'] == 2) {
                $field = '_qq_';
            } else {
                $field = '_wb_';
            }
            if($userInfo["user{$field}token"]) {
                return json(['status' => 0, 'msg' => '此号码已被绑定']);
            }
        }
        $startTime = strtotime(date('Y-m-d 00:00:00'));//当天的起始时间
        $endTime = strtotime(date('Y-m-d 23:59:59'));//当天的结束时间
        $where = [];
        $where['phone'] = $params['phone'];
        $where['time'] = ['between', [$startTime, $endTime]];
        $num = Db::table('up_phonecode')->where($where)->count('id');
        if($num == 5) {
            return json(['status' => 0, 'msg' => '短信验证码今日已发送5次，请明天再来']);
        }
        $code = GetRandCode();//6位数验证码
        $code = 123456;//6位数验证码
        $templateid = config('yzx')['templateid'];
        $sendres = YzxSms($templateid,$code, $params['phone'], '');//发送验证码
        if($sendres['code'] != '00000') {//发送不成功
            return json(['status' => 0, 'msg' => $sendres['msg']]);
        } else {
            $data = [
                'phone' => $params['phone'],//发送的手机号
                'code' => $code,//验证码
                'time' => time(),//验证码发送的时间戳
                'date_time' => date('Y-m-d H:i:s')//日期格式
            ];
            $res = Db::table('up_phonecode')->insert($data);
            if(!$res) {
                return json(['status' => 0, 'msg' => '数据库操作失败']);
            }
            return json(['status' => 200, 'msg' => $code]);
        }
    }
    
    /**
     * 注册--------暂时用不到
     * @return bool
     * regist_type  注册类型  1 正常注册  2 第三方登录时没有注册过，直接注册登录
     * phone  手机号
     * code  验证码
     * password  密码
     * user_type  角色  1 学生  2 老师
     * grade_id  年级ID
     * third_type   第三方登录的种类   1 微信  2 qq  3 微博
     * name  第三方昵称
     * image  第三方头像
     * thirdToken  第三方token
     */
    public function phoneRegister()
    {
        $phone = input('phone');//手机号
        $user_type = input('user_type');//角色
        $grade_id = input('grade_id');//年级ID
        $token = md5(date('YmdHis') . rand(100000, 999999));
    
        $data = [
            'user_phone' => $phone,
            'user_token' => $token,
            'user_time' => date('Y-m-d H:i:s'),//注册时间
            'user_type' => $user_type,//角色
            'user_y_m' => date('Y-m')
        ];
        //学生不需要审核,需要选择年级
        if($user_type == 1) {
            $date['user_status'] = 1;
            $data['user_grade'] = $grade_id;//年级
        }
        
        if(input('regist_type') == 1){//正常注册
            $code = input('code');//验证码
            $password = trim(input('password'), ' ');//密码
            if($phone == '' || $code == '' || $password == '') {
                return json(['status' => 0, 'msg' => '有未填项，请检查']);
            }
            //验证手机号
            if(!preg_match("/^1[3456789]\d{9}$/", $phone)) {
                return json(['status' => 0, 'msg' => '请输入正确的手机号']);
            }
            $username = Db::table('up_u_user')->where('user_phone', $phone)->find();
            if(!empty($username)) {
                return json(['status' => 0, 'msg' => '此手机号码已注册']);
            }
            //验证验证码
            $res = Db::table('up_phonecode')
                ->where('phone', $phone)
                ->order('time desc')
                ->limit(1)
                ->find();
            if($code != $res['code']) {
                return json(['status' => 0, 'msg' => '验证码错误']);
            }
            $now = time();
            if($now - $res['time'] >= 1801) {
                return json(['status' => 0, 'msg' => '验证码超时']);
            }
            if($res['status'] == 1) {
                return json(['status' => 0, 'msg' => '验证码已使用']);
            }
            $data['user_password'] = md5($password);
            $user_id = Db::name('u_user')->insertGetId($data);
            //修改验证码状态
            Db::table('up_phonecode')->where('id', $res['id'])->setField('status', 1);
        }else{//第三方登录时注册
            if(input('third_type') == 1) {
                $field = '_wx_';
            } elseif(input('third_type') == 2) {
                $field = '_qq_';
            } else {
                $field = '_wb_';
            }
            $data["user{$field}token"] = input('thirdToken');
            $data["user{$field}nickname"] = input('name');
            $data["user{$field}image"] = input('image');
            $user_id = Db::name('u_user')->insertGetId($data);
            //更新用户头像、名称为第三方昵称、头像
            $update['user_username'] = input('name');
            $update['user_image'] = input('image');
            if($user_id){
                Db::table('up_u_user')->where('user_id', $user_id)->update($update);
            }
        }
        
        if($user_id) {
            //插入学校、年级、班级关联表
            if($user_type == 1){
                Db::table('up_grade_class')->insert([
                    'gs_user_id' => $user_id,
                    'gs_grade_id' => $grade_id,
                    'gs_role' => 1
                ]);
            }
            //注册成功后自动登录
            $userInfo = Db::table('up_u_user')
                ->where('user_id', $user_id)
                ->find();
            return json(['status' => 200, 'msg' => $userInfo]);
        } else {
            return json(['status' => 0, 'msg' => '注册失败']);
        }
    }
    
    /**
     * 用户正常注册
     * @return \think\response\Json
     * phone    手机号
     * code     验证码
     * password 密码
     */
    public function userRegist(){
        $phone = trim(input('phone'), ' ');
        $code = input('code');
        $password = trim(input('password'), ' ');
        
        if($phone == '' || $code == '' || $password == '') {
            return json(['status' => 0, 'msg' => '有未填项，请检查']);
        }
        
        //验证手机号
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)) {
            return json(['status' => 0, 'msg' => '请输入正确的手机号']);
        }
        $username = Db::table('up_u_user')->where('user_phone', $phone)->find();
        if(!empty($username)) {
            return json(['status' => 0, 'msg' => '此手机号码已注册']);
        }
        
        //验证验证码
        $res = Db::table('up_phonecode')
            ->where('phone', $phone)
            ->order('time desc')
            ->limit(1)
            ->find();
        if($code != $res['code']) {
            return json(['status' => 0, 'msg' => '验证码错误']);
        }
        $now = time();
        if($now - $res['time'] >= 1801) {
            return json(['status' => 0, 'msg' => '验证码超时']);
        }
        if($res['status'] == 1) {
            return json(['status' => 0, 'msg' => '验证码已使用']);
        }
        
        $token = md5(date('YmdHis') . rand(100000, 999999));
        $data['user_password'] = md5($password);
        $data['user_phone'] = $phone;
        $data['user_time'] = date('Y-m-d H:i:s');
        $data['user_y_m'] = date('Y-m');
        $data['user_token'] = $token;
        $user_id = Db::name('u_user')->insertGetId($data);
        if($user_id){
            //修改验证码状态
            Db::table('up_phonecode')->where('id', $res['id'])->setField('status', 1);
            //注册成功后自动登录
            $userInfo = Db::table('up_u_user')->where('user_id', $user_id)->find();
            $rytoken = $this->rongyun($userInfo['user_id'],'who',$userInfo['user_image']);
            $userInfo['rytoken'] = $rytoken['token'];
            return json(['status' => 200, 'msg' => $userInfo]);
        }else{
            return json(['status' => 0, 'msg' => '注册失败']);
        }
    }
    
    /**
     * 用户第三方登录时注册
     * @return \think\response\Json
     * phone          手机号
     * code           验证码
     * thirdToken     第三方token
     * name           第三方昵称
     * image          第三方头像
     * third_type     第三方类型   1 微信  2 qq  3 微博
     *
     */
    public function thirdRegist(){
        $phone = trim(input('phone'), ' ');
        $code = input('code');
//        $password = trim(input('password'), ' ');
        if(input('third_type') == 1) {
            $field = '_wx_';
        } elseif(input('third_type') == 2) {
            $field = '_qq_';
        } else {
            $field = '_wb_';
        }
        
        if($phone == '' || $code == '') {
            return json(['status' => 0, 'msg' => '有未填项，请检查']);
        }
        //验证手机号
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)) {
            return json(['status' => 0, 'msg' => '请输入正确的手机号']);
        }
        $username = Db::table('up_u_user')->where('user_phone', $phone)->find();
//        if(!empty($username)) {
//            return json(['status' => 0, 'msg' => '此手机号码已注册']);
//        }
        
        //验证验证码
        $res = Db::table('up_phonecode')
            ->where('phone', $phone)
            ->order('time desc')
            ->limit(1)
            ->find();
        if($code != $res['code']) {
            return json(['status' => 0, 'msg' => '验证码错误']);
        }
        $now = time();
        if($now - $res['time'] >= 1801) {
            return json(['status' => 0, 'msg' => '验证码超时']);
        }
        if($res['status'] == 1) {
            return json(['status' => 0, 'msg' => '验证码已使用']);
        }
        
        $token = md5(date('YmdHis') . rand(100000, 999999));
//        $data['user_password'] = md5($password);
        $data['user_phone'] = $phone;
        $data['user_time'] = date('Y-m-d H:i:s');
        $data['user_y_m'] = date('Y-m');
        $data['user_token'] = $token;
        $data["user{$field}token"] = input('thirdToken');
        $data["user{$field}nickname"] = input('name');
        $data["user{$field}image"] = input('image');
        //更新用户头像、名称为第三方昵称、头像
        $data['user_username'] = input('name');
        $data['user_image'] = input('image');
        $user_id = Db::name('u_user')->insertGetId($data);
        
        if($user_id){
            //修改验证码状态
            Db::table('up_phonecode')->where('id', $res['id'])->setField('status', 1);
            //注册成功后自动登录
            $userInfo = Db::table('up_u_user')->where('user_id', $user_id)->find();
            $rytoken = $this->rongyun($userInfo['user_id'],'who',$userInfo['user_image']);
            $userInfo['rytoken'] = $rytoken['token'];
            return json(['status' => 200, 'msg' => $userInfo]);
        }else{
            return json(['status' => 0, 'msg' => '注册失败']);
        }
    }
    
    /**
     * 用户选择角色和年级
     * @return \think\response\Json
     * user_id     用户ID
     * role        用户选择的角色   1 学生   2 老师
     * grade_id    用户选择的年龄    role为1时传
     */
    public function chooseRole(){
        $user_id = input('user_id');
        $role = input('role');//角色  1 学生   2 老师
    
        Db::startTrans();
        try{
            $is_in= Db::table('up_grade_class')->where('gs_user_id', $user_id)->find();
            //如果有该用户的信息，则说明用户不是第一次选择角色，并且第一次选择的是学生
            if($is_in){
                if($role == 1){//这次又选了学生
                    $grade_id = input('grade_id');
                    //比较2次选择的年级是否相同，如果不相同，则更新数据
                    if($grade_id != $is_in['gs_grade_id']){
                        Db::table('up_grade_class')->where('gs_user_id', $user_id)->update(['gs_grade_id' => $grade_id]);
                        Db::table('up_u_user')->where('user_id', $user_id)->update(['user_grade' => $grade_id]);
                    }
                }else{//这次选了老师
                    //删除关联表数据
                    Db::table('up_grade_class')->where('gs_user_id', $user_id)->delete();
                    //更新用户表数据
                    Db::table('up_u_user')->where('user_id', $user_id)->update([
                        'user_type' => $role,
                        'user_grade' => null,
                        'user_status' => 6
                    ]);
                }
            }else{//说明是第一次选择或之前一次选择的是老师
                if($role == 1){//这次选择的是学生
                    //关联表数组
                    $insert = [
                        'gs_user_id' => $user_id,
                        'gs_grade_id' => input('grade_id'),
                        'gs_role' => $role
                    ];
                    Db::table('up_grade_class')->insert($insert);
                    //更新用户表
                    Db::table('up_u_user')->where('user_id', $user_id)->update([
                        'user_type' => $role,
                        'user_grade' => input('grade_id'),
                        'user_status' => 1
                    ]);
                }else{
                    Db::table('up_u_user')->where('user_id', $user_id)->update(['user_type' => $role,'user_status'=>6]);
                }
            }
            
            Db::commit();
            $res = 1;
        }catch(\Exception $e){
            Db::rollback();
            $res = 0;
        }
        if($res){
            $info = Db::table('up_u_user')->where('user_id', $user_id)->find();
            $rytoken = $this->rongyun($info['user_id'],'who',$info['user_image']);
            $info['rytoken'] = $rytoken['token'];
            return json(['status' => 200, 'msg' => $info]);
        }else{
            return json(['status' => 0, 'msg' => false]);
        }
        
        
    }
    
    /**
     * 手机号+密码登录
     * @return bool
     * phone  手机号
     * password  密码
     */
    public function userLogin()
    {
        $phone = input('phone');
        $password = trim(input('password'));
        if($phone == '') {
            return json(['status' => 0, 'msg' => '请输入手机号']);
        }
        if($password == '') {
            return json(['status' => 0, 'msg' => '请输入密码']);
        }
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)) {
            return json(['status' => 0, 'msg' => '请输入正确的手机号']);
        }
        $userInfo = Db::table('up_u_user')->where('user_phone', $phone)->find();
        if(empty($userInfo)) {
            return json(['status' => 0, 'msg' => '该账号不存在']);
        }
        if(md5($password) != $userInfo['user_password']) {
            return json(['status' => 0, 'msg' => '密码错误']);
        }
        if($userInfo['user_status'] == 3) {
            return json(['status' => 0, 'msg' => '该账号已被冻结']);
        }
        if($userInfo['user_status'] == 4) {
            return json(['status' => 0, 'msg' => '该账号已被删除，请联系管理员']);
        }
        
        $token = md5(date('YmdHis') . rand(100000, 999999));
        $update = [
            'user_token' => $token,
        ];
        $result = Db::table('up_u_user')->where('user_phone', $phone)->update($update);
        if($result) {
            $user = Db::table('up_u_user')->where('user_phone', $phone)->find();
            //如果没有选择角色，则跳转到选择角色页面
            if(empty($user['user_type'])){
                return json(['status' => 400, 'msg' => $user]);
            }
//            if($user['user_id'] == 8){
//                $user['user_id'] = 'tangzhifeng';
//            }
            $rytoken = $this->rongyun("{$user['user_id']}",'who8',$user['user_image']);
            $user['rytoken'] = $rytoken['token'];
            $user['user_f_online'] = 1;
            return json(['status' => 200, 'msg' => $user]);
        } else {
            return json(['status' => 0, 'msg' => '登录失败']);
        }
        
    }
    
    /**
     * 短信快捷登录
     * @return bool
     * phone  手机号
     * code  验证码
     */
    public function phoneLogin()
    {
        $phone = trim(input('phone'), ' ');
        $code = trim(input('code'), ' ');
        
        if($phone == '') {
            return json(['status' => 0, 'msg' => '请输入手机号码']);
        }
        if($code == '') {
            return json(['status' => 0, 'msg' => '请输入验证码']);
        }
        if(!preg_match("/^1[34578]\d{9}$/", $phone)) {
            return json(['status' => 0, 'msg' => '请输入正确的手机号']);
        }
        $userInfo = Db::table('up_u_user')->where('user_phone', $phone)->find();
        if(empty($userInfo)) {
            return json(['status' => 0, 'msg' => '该账号不存在']);
        }
        
        $res = Db::table('up_phonecode')
            ->where('phone', $phone)
            ->order('time desc')
            ->limit(1)
            ->find();
        if($code != $res['code']) {
            return json(['status' => 0, 'msg' => '验证码错误']);
        }
        $now = time();
        if($now - $res['time'] >= 1801) {
            return json(['status' => 0, 'msg' => '验证码超时']);
        }
        if($res['status'] == 1) {
            return json(['status' => 0, 'msg' => '验证码已使用']);
        }
        
        if($userInfo['user_status'] == 3) {
            return json(['status' => 0, ' msg' => '该账号已被冻结']);
        }
        if($userInfo['user_status'] == 4) {
            return json(['status' => 0, ' msg' => '该账号已被删除，请联系管理员']);
        }
        //更新token
        $token = md5(date('YmdHis') . rand(100000, 999999));
        $update = [
            'user_token' => $token,
        ];
        $result = Db::table('up_u_user')->where('user_phone', $phone)->update($update);
        if($result) {
            $username = Db::table('up_u_user')->where('user_phone', $phone)->find();
            Db::table('up_phonecode')->where('id', $res['id'])->update(['status' => 1]);
            //如果没有选择角色，则跳转到选择角色页面
            if(empty($username['user_type'])){
                return json(['status' => 400, 'msg' => $username]);
            }
            $rytoken = $this->rongyun($username['user_id'],'who',$username['user_image']);
            $username['rytoken'] = $rytoken['token'];
            $username['user_f_online'] = 1;
            return json(['status' => 200, 'msg' => $username]);
        } else {
            return json(['status' => 0, 'msg' => '登录失败']);
        }
    }
    
    /**
     * 微信||QQ||微博
     * thirdToken  第三方token
     * phone  手机号
     * code  验证码
     * name  第三方昵称
     * image  第三方头像
     * type  第三方类型   1 微信  2 qq  3 微博
     * @return string
     */
    public function thirdLogin()
    {
        $thirdToken = input('thirdToken');
        $name = input('name');
        $image = input('image');
        $type = input('type');
        if($type == 1) {
            $field = '_wx_';
        } elseif($type == 2) {
            $field = '_qq_';
        } else {
            $field = '_wb_';
        }
        $where["user{$field}token"] = $thirdToken;
        $isFirstLogin = Db::table('up_u_user')->where($where)->find();
        //---------------是否是第一次使用同类型的第三方登录-------
        if($isFirstLogin) {//已经用同类第三方登录过，直接登录
            //如果没有选择过角色，则跳转到选择角色页面
            if(empty($isFirstLogin['user_type'])){
                return json(['status' => 400, 'msg' => $isFirstLogin]);
            }else{
                //更新token
                $token = md5(date('YmdHis') . rand(100000, 999999));
                $update = [
                    'user_token' => $token,
                ];
                $result = Db::table('up_u_user')->where($where)->update($update);
                $isFirstLogin = Db::table('up_u_user')->where($where)->find();
                $rytoken = $this->rongyun($isFirstLogin['user_id'],'who',$isFirstLogin['user_image']);
                $isFirstLogin['rytoken'] = $rytoken['token'];
                $isFirstLogin['user_f_online'] = 1;
                return json(['status' => 300, 'msg' => $isFirstLogin]);
            }
        } else {//没有用同类第三方登录过，去绑定手机号
            $phone = trim(input('phone'), ' ');
            $code = trim(input('code'), ' ');
            $token = md5(date('YmdHis') . rand(100000, 999999));
            if($code == '' || $phone == '') {
                return json(['status' => 0, 'msg' => '有未填项，请检查']);
            }
            if(!preg_match("/^1[3456789]\d{9}$/", $phone)) {
                return json(['status' => 0, 'msg' => '请填写正确的手机号码']);
            }
            $userInfo = Db::table('up_u_user')->where('user_phone', $phone)->find();
            
            //如果账号不存在，则返回100，用于判断是否跳到选择角色、完善信息页面
            if(empty($userInfo)) {
                return json(['status' => 100, 'msg' => '']);
//                $date = [
//                    'user_token' => $token,
//                    'user' . $field . 'token' => $thirdToken,
//                    'user' . $field . 'nickname' => $name,
//                    'user' . $field . 'image' => $image,
//                    'user_phone' => $phone
//                ];
//                $insert_id = Db::table('up_u_user')->insertGetId($date);
//                if($insert_id){
//                    $user_info = Db::table('up_u_user')->where('user_id', $insert_id)->find();
//                    return json(['status' => 100, 'msg' => $user_info]);
//                }else{
//                    return json(['status' => 0, 'msg' => '登录失败']);
//                }
            }
            
            if($userInfo['user_status'] == 3) {
                return json(['status' => 0, ' msg' => '该账号已被冻结']);
            }
            if($userInfo['user_status'] == 4) {
                return json(['status' => 0, ' msg' => '该账号已被删除，请联系管理员']);
            }
            if($userInfo["user{$field}token"]) {
                return json(['status' => 0, 'msg' => '该手机号已被绑定，需解绑后重新绑定']);
            }
            $res = Db::table('up_phonecode')
                ->where('phone', $phone)
                ->order('time desc')
                ->limit(1)
                ->find();
            if($code != $res['code']) {
                return json(['status' => 0, 'msg' => '验证码错误']);
            }
            $now = time();
            if($now - $res['time'] >= 1801) {
                return json(['status' => 0, 'msg' => '验证码失效']);
            }
            if($res['status'] == 1) {
                return json(['status' => 0, 'msg' => '验证码已使用']);
            }
            
            $update = [
                'user_token' => $token,
                'user' . $field . 'token' => $thirdToken,
                'user' . $field . 'nickname' => $name,
                'user' . $field . 'image' => $image,
            ];
            //如果用户没有昵称、头像信息，则更新为第三方昵称、头像
            if(!$userInfo['user_username']) {
                $update['user_username'] = $name;
            }
            if(!$userInfo['user_image']) {
                $update['user_image'] = $image;
            }
            $res1 = Db::table('up_u_user')->where('user_phone', $phone)->update($update);//更新用户信息
            if($res1) {
                $userData = Db::table('up_u_user')->where('user_phone', $phone)->find();
                //如果没有选择角色，则跳转到选择角色页面
                if(empty($userData['user_type'])){
                    return json(['status' => 400, 'msg' => $userData]);
                }
                Db::table('up_phonecode')->where('id', $res['id'])->update(['status' => 1]);//改变验证码状态
                $rytoken = $this->rongyun($userData['user_id'],'who',$userData['user_image']);
                $userData['rytoken'] = $rytoken['token'];
                $userData['user_f_online'] = 1;
                return json(['status' => 200, 'msg' => $userData]);
            } else {
                return json(['status' => 0, 'msg' => '绑定失败']);
            }
        }
    }
    
    /**
     * 忘记密码第一步
     * @return bool
     * phone  手机号
     * code  验证码
     */
    public function forgetFirst()
    {
        $phone = trim(input('phone'), ' ');
        $code = trim(input('code'), ' ');
        
        if($phone == '') {
            return json(['status' => 0, 'msg' => '请输入手机号码']);
        }
        if($code == '') {
            return json(['status' => 0, 'msg' => '请输入验证码']);
        }
        if(!preg_match("/^1[34578]\d{9}$/", $phone)) {
            return json(['status' => 0, 'msg' => '请输入正确的手机号']);
        }
        $userInfo = Db::table('up_u_user')->where('user_phone', $phone)->find();
        if(empty($userInfo)) {
            return json(['status' => 0, 'msg' => '该账号不存在']);
        }
        
        $res = Db::table('up_phonecode')
            ->where('phone', $phone)
            ->order('time desc')
            ->limit(1)
            ->find();
        if($code != $res['code']) {
            return json(['status' => 0, 'msg' => '验证码错误']);
        }
        $now = time();
        if($now - $res['time'] >= 1801) {
            return json(['status' => 0, 'msg' => '验证码超时']);
        }
        if($res['status'] == 1) {
            return json(['status' => 0, 'msg' => '验证码已使用']);
        }
        
        if($userInfo['user_status'] == 3) {
            return json(['status' => 0, ' msg' => '该账号已被冻结']);
        }
        if($userInfo['user_status'] == 4) {
            return json(['status' => 0, ' msg' => '该账号已被删除，请联系管理员']);
        }
        Db::table('up_phonecode')->where('id', $res['id'])->update(['status' => 1]);
        $username = Db::table('up_u_user')->where('user_phone', $phone)->find();
        return json(['status' => 200, 'msg' => $username]);
    }
    
    /**
     * 忘记密码第二步
     * @return bool
     * password  密码
     * verify_password  验证密码
     * user_id  用户ID
     */
    public function forgetSecond()
    {
        $password = trim(input('password'), ' ');
        $verify_password = trim(input('verify_password'), ' ');
        $user_id = input('user_id');
        
        if($password == '') {
            return json(['status' => 0, 'msg' => '请输入密码']);
        }
        if($verify_password == '') {
            return json(['status' => 0, 'msg' => '请输入确认密码']);
        }
        if($password != $verify_password){
            return json(['status' => 0, 'msg' => '两次输入的密码不一样']);
        }
        $token = md5(date('YmdHis') . rand(100000, 999999));
        $update = [
            'user_token' => $token,
            'user_password' => md5($password)
        ];
        $res = Db::table('up_u_user')
            ->where('user_id', $user_id)
            ->update($update);
        if($res){
            $userInfo = Db::table('up_u_user')->where('user_id', $user_id)->find();
            //如果没有选择角色，则跳转到选择角色页面
            if(empty($userInfo['user_type'])){
                return json(['status' => 400, 'msg' => $userInfo]);
            }
            $rytoken = $this->rongyun($userInfo['user_id'],'who',$userInfo['user_image']);
            $userInfo['rytoken'] = $rytoken['token'];
            $userInfo['user_f_online'] = 1;
            return json(['status' => 200, 'msg' => $userInfo]);
        }else{
            return json(['status' => 0, 'msg' => '修改密码失败']);
        }
    }
    
    /**
     * 修改密码
     * @return \think\response\Json
     * new_password  新密码
     * verify_password  确认密码
     * user_id  用户ID
     */
    public function changePassword(){
        $new_password = trim(input('new_password'), ' ');
        $verify_password = trim(input('verify_password'), ' ');
        $user_id = input('user_id');
        
        if($new_password == ''){
            return json(['status' => 0, 'msg' => '请填写新密码']);
        }
        if($verify_password == ''){
            return json(['status' => 0, 'msg' => '请填写确认密码']);
        }
        if($new_password != $verify_password){
            return json(['status' => 0, 'msg' => '两次输入的密码不一致']);
        }
        
        $update['user_password'] = md5($new_password);
        $res = Db::name('u_user')->where('user_id', $user_id)->update($update);
        if($res){
            return json(['status' => 200, 'msg' => '修改成功']);
        }else{
            return json(['status' => 0, 'msg' => '修改失败']);
        }
    }
    
    /**
     * 修改手机号第一步
     * @return \think\response\Json
     * phone  用户手机号
     * code  验证码
     */
    public function changePhoneF(){
        $phone = input('phone');
        $code = input('code');
        
        if($code == '') {
            return json(['status' => 0, 'msg' => '请输入验证码']);
        }
        $res = Db::table('up_phonecode')
            ->where('phone', $phone)
            ->order('time desc')
            ->limit(1)
            ->find();
        if($code != $res['code']) {
            return json(['status' => 0, 'msg' => '验证码错误']);
        }
        $now = time();
        if($now - $res['time'] >= 1801) {
            return json(['status' => 0, 'msg' => '验证码超时']);
        }
        if($res['status'] == 1) {
            return json(['status' => 0, 'msg' => '验证码已使用']);
        }
        $result = Db::table('up_phonecode')->where('id', $res['id'])->update(['status' => 1]);
        
        if($result){
            return json(['status' => 200, 'msg' => '']);
        }else{
            return json(['status' => 0, 'msg' => '操作数据库错误']);
        }
    }
    
    /**
     * 修改手机号第二步
     * @return \think\response\Json
     * user_id  用户ID
     * phone  用户手机号
     * code  验证码
     */
    public function changePhoneS(){
        $phone = input('phone');
        $code = input('code');
        $user_id = input('user_id');
    
        if($phone == '') {
            return json(['status' => 0, 'msg' => '请输入手机号码']);
        }
        
        if($code == '') {
            return json(['status' => 0, 'msg' => '请输入验证码']);
        }
        
        if(!preg_match("/^1[34578]\d{9}$/", $phone)) {
            return json(['status' => 0, 'msg' => '请输入正确的手机号']);
        }
        
        $info = Db::table('up_u_user')->where('user_phone', $phone)->find();
        if($info){
            return json(['status' => 0, 'msg' => '该手机号已注册']);
        }
        
        $res = Db::table('up_phonecode')
            ->where('phone', $phone)
            ->order('time desc')
            ->limit(1)
            ->find();
        if($code != $res['code']) {
            return json(['status' => 0, 'msg' => '验证码错误']);
        }
        $now = time();
        if($now - $res['time'] >= 1801) {
            return json(['status' => 0, 'msg' => '验证码超时']);
        }
        if($res['status'] == 1) {
            return json(['status' => 0, 'msg' => '验证码已使用']);
        }
        
        $result = Db::table('up_u_user')->where('user_id', $user_id)->update(['user_phone' => $phone]);
        
        if($result){
            Db::table('up_phonecode')->where('id', $res['id'])->update(['status' => 1]);
            return json(['status' => 200, 'msg' => '修改成功']);
        }else{
            return json(['status' => 0, 'msg' => '修改失败']);
        }
    }
    
    /**
     * 用户协议
     * @return \think\response\Json
     */
    public function agreement(){
        $agreement = Db::table('up_about')->where('id', 2)->value('content');
        return json(['status' => 200, 'msg' => $agreement]);
    }
    /***
     *
     * 分享：知识对战——获取俩人的信息
     */
    public function getTwoIdInfo(){
        header('Access-Control-Allow-Origin:*');
        extract(input());
        $other = Db::table('up_u_user u')
            ->join ('up_exp_level l','u.user_level = l.el_id','LEFT')
            ->join ('up_grade g','u.user_grade = g.grade_id','LEFT')
            ->where('user_id',$uid)
            ->field('user_id,user_type,user_username,user_image,user_age,user_gender,user_birthday,user_f_all,user_f_win,el_name,grade_name')
            ->find();
        if($other['user_type'] == 2){
            $other['grade_name'] = '老师';
        }
        $my = Db::table('up_u_user u')
            ->join ('up_exp_level l','u.user_level = l.el_id','LEFT')
            ->join ('up_grade g','u.user_grade = g.grade_id','LEFT')
            ->where('user_id',$user_id)
            ->field('user_id,user_type,user_username,user_image,user_age,user_gender,user_birthday,user_f_all,user_f_win,el_name,grade_name')
            ->find();
        if($my['user_type'] == 2){
            $my['grade_name'] = '老师';
        }
        return json(array('status' => 200, 'other' => $other, 'my' => $my));
    }
}